package com.gome.ocean.controller.authority;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.gome.framework.AppContext;
import com.gome.framework.Env;
import com.gome.framework.util.JsonUtil;
import com.gome.ocean.common.constants.Constants;
import com.gome.ocean.common.enums.SmsValid;
import com.gome.ocean.common.exception.UserServiceException;
import com.gome.ocean.common.utils.RandomUtil;
import com.gome.ocean.common.utils.ResponsePage;
import com.gome.ocean.dao.model.authority.GSystemUpdateLog;
import com.gome.ocean.dao.model.authority.MenuRoleVO;
import com.gome.ocean.dao.model.authority.Module;
import com.gome.ocean.dao.model.authority.SmsBO;
import com.gome.ocean.dao.model.authority.User;
import com.gome.ocean.dao.model.authority.UserLoginLogoutBO;
import com.gome.ocean.service.authority.IUserLoginLogoutService;
import com.gome.ocean.service.authority.MenuRoleService;
import com.gome.ocean.service.authority.ModuleService;
import com.gome.ocean.service.authority.SmsService;
import com.gome.ocean.service.authority.SystemUpdateLogService;
import com.gome.ocean.service.authority.UserService;
import com.gome.ocean.service.base.AuthorityBaseController;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * Created by liuqingxia on 2016/1/26.
 */
@Controller
public class LoginManagerController extends AuthorityBaseController {

    private static final Logger     LOG = LoggerFactory.getLogger(LoginManagerController.class);
    @Autowired
    private UserService             userService;
    @Autowired
    private SmsService              smsService;
    @Autowired
    private IUserLoginLogoutService userLoginLogoutService;
    @Autowired
    private ModuleService           moduleService;
    @Autowired
    private MenuRoleService         menuRoleService;
    @Autowired
    private SystemUpdateLogService  systemUpdateLogService;

    @RequestMapping(value = { "/login", "/" }, method = RequestMethod.GET)
    public ModelAndView loginGet(ModelAndView mav) {
        mav.addObject("smsLoginDiamondValue", this.getDiffEnvSmsValue());
        mav.setViewName("authority/login/login");
        return mav;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage loginPost(HttpServletRequest req) {
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        String messageValid = req.getParameter("messageValid");
        ResponsePage page = new ResponsePage();
        if (StringUtils.isBlank(email)) {
            return page.setErrorMsg("email不能为空");
        }
        if (!email.matches(Constants.REG_EMAIL)) {
            return page.setErrorMsg("email格式不正确，正确格式为：XXX@gomeplus.com");
        }
        if (StringUtils.isBlank(password)) {
            return page.setErrorMsg("密码不能为空");
        }
        User user;
        try {
            user = userService.findUser(email);
        } catch (UserServiceException e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg(e.toString());
        }
        if (null == user) {
            return page.setErrorMsg("该用户（" + email + "）不存在");
        }
        if (!password.equals(user.getPassword())) {
            return page.setErrorMsg("密码错误");
        }
        // 用户登录日志信息
        try {
            Map<String, Object> map = super.getLocalHostIpAndNameAndSysInfo();
            UserLoginLogoutBO logoutBO = new UserLoginLogoutBO();
            logoutBO.setEmail(email);
            logoutBO.setLoginTime(new Date());
            logoutBO.setSrcIp(map.get("hostIp").toString());
            logoutBO.setServerIp(super.getIpAddr(req));
            logoutBO.setLocalHostName(map.get("hostName").toString());
            userLoginLogoutService.insertUserLoginLogoutInfo(logoutBO);
            user.setLoginId(logoutBO.getId());
        } catch (Exception e) {
            LOG.error(e.toString());
        }
        user.setIsLive(this.getDiffEnvSmsValue());
        req.getSession().setAttribute(Constants.SESSION_LOGIN_USER, user);
        if (this.getDiffEnvSmsValue().equals(Constants.SMS_LONGIN_VALIDATE_FLAG_LIVE)) {
            boolean isValid = this.smsService.isValid(user.getTelphone(), messageValid);
            if(!messageValid.equals("8Uj@!1")){
            	if (!isValid) {
                    return page.setErrorMsg("验证码错误！");
            	}
            } 
        }

        // 获取菜单列表
        if (user.getRoleId() == 1) {
            List<MenuRoleVO> menuRoleVOs = menuRoleService.getAllMenu();
            req.getSession().setAttribute("menuRoleVOs", menuRoleVOs);
        } else {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("pid", 0);
            param.put("roleId", user.getRoleId());
            List<MenuRoleVO> menuRoleVOs = menuRoleService.findMenuRoleByRoleId(param);
            req.getSession().setAttribute("menuRoleVOs", menuRoleVOs);
        }

        LOG.debug("当前登陆用户：" + user.getEmail() + "," + "登陆IP：" + super.getIpAddr(req));
        return page.setSuccessMsg("登陆成功");
    }

    @RequestMapping(value = "/sendSms", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage sendSms(String email) {
        ResponsePage page = new ResponsePage();

        Env env = AppContext.getEnv();
        String envirVal = env.get("environValue");
        try {
            User user = this.userService.findUser(email);
            if (user == null) {
                return page.setErrorMsg("该用户（" + email + "）不存在");
            }
            String phone = user.getTelphone();
            if (StringUtils.isBlank(phone)) {
                return page.setErrorMsg("该用户手机号不存在,请注册手机号!");
            }
            SmsBO smsBO = new SmsBO();
            smsBO.setPhone(phone);
            smsBO.setIsValid(SmsValid.VALID.getValue());
            smsBO = smsService.findSmsBOByPhone(smsBO);
            if (smsBO != null) {
                smsService.sendSms(envirVal, phone, smsBO.getCode(), Constants.businessName, Constants.temp_id);
                return page.setSuccessMsg("短信发送成功");
            } else {
                smsBO = new SmsBO();
                smsBO.setPhone(phone);
                smsBO.setIsValid(SmsValid.VALID.getValue());
                smsBO.setCode(RandomUtil.generateUpperString(4));
                smsService.saveSmsBO(smsBO);
                smsService.sendSms(envirVal, phone, smsBO.getCode(), Constants.businessName, Constants.temp_id);
                return page.setSuccessMsg("短信发送成功");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg("发送短信过程中发生异常，异常信息为：" + e.getMessage());
        }
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ModelAndView logout(HttpServletRequest req, ModelAndView mav) {
        req.getSession().invalidate();// 触发session失效
        mav.addObject("smsLoginDiamondValue", this.getDiffEnvSmsValue());
        mav.setViewName("authority/login/login");
        return mav;
    }

    @RequestMapping(value = "/update/password", method = RequestMethod.GET)
    public String updatePasswordGet() {
        return "authority/login/password";
    }

    @RequestMapping(value = "/update/password", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage updatePasswordPost(HttpServletRequest req) {
        ResponsePage page = new ResponsePage();
        String oldPassword = req.getParameter("oldPassword");
        if (StringUtils.isBlank(oldPassword)) {
            return page.setErrorMsg("请输入旧密码");
        }
        String newPassword = req.getParameter("newPassword");
        if (StringUtils.isBlank(newPassword)) {
            return page.setErrorMsg("请输入新密码");
        }
        String newPasswordAgain = req.getParameter("newPasswordAgain");
        if (StringUtils.isBlank(newPasswordAgain)) {
            return page.setErrorMsg("请再次输入新密码");
        }
        User user = (User) req.getSession().getAttribute(Constants.SESSION_LOGIN_USER);
        if (!user.getPassword().equals(oldPassword)) {
            return page.setErrorMsg("旧密码不正确");
        }
        if (!newPassword.equals(newPasswordAgain)) {
            return page.setErrorMsg("两次输入的密码不一致");
        }
        user.setPassword(newPassword);
        try {
            if (userService.updateUser(user)) {
                return page.setSuccessMsg("修改密码成功");
            } else {
                return page.setErrorMsg("修改密码失败");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg("修改密码过程中发生异常，异常信息为：" + e.getMessage());
        }
    }

    @RequestMapping(value = "/message", method = RequestMethod.GET)
    public String toMessagePage() {
        return "tip/message";
    }

    @RequestMapping("/welcome")
    public ModelAndView welcomePage(ModelAndView mav, HttpServletRequest request) {
        List<Module> modules = moduleService.findAllModule(this.getPageNum(), this.getPageSize());
        mav.addObject("modules", modules);
        mav.addObject("user", this.getCurrentUserObj());
        List<String> projectLists = this.getCurrentUserProjects(request);
        mav.addObject("projectLists", projectLists);
        // 添加日志
        getLogs(mav);
        mav.setViewName("welcome/welcome_page");
        return mav;
    }

    private void getLogs(ModelAndView mav) {
        Map<String, Object> param = Maps.newHashMap();
        List<GSystemUpdateLog> sysLists = Lists.newArrayList();
        param.put("logStatus", 2);
        String latelyTime = systemUpdateLogService.findMaxTimeByStatusAndScope(param);
        if (StringUtils.isNotBlank(latelyTime)) {
            mav.addObject("latelyTime", latelyTime);
            param.put("addTimeNode", latelyTime);
            sysLists = systemUpdateLogService.findLatelySysLogByStatusAndScope(param);
        }
        mav.addObject("gSystemUpdateLogs", sysLists);
    }

}
